1、整合JDBC

1.1、搭建项目环境

1.1.1、创建表
1
2
3
4
5
CREATE TABLE `test`.`user` (
`userid` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(30) NULL,
`usersex` VARCHAR(10) NULL,
PRIMARY KEY (`userid`));
1.1.2、创建项目

在这里插入图片描述

1.1.3、修改POM文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xiezhenyu</groupId>
<artifactId>springbootjdbc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootjdbc</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Thymeleaf启动器坐标 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- jdbc启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mysql数据库驱动坐标 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

1.2、配置数据源

1.2.1、通过自定义配置文件方式配置数据源信息
1.2.1.1、通过@PropertySource注解读取配置信息
  • 添加Druid数据源依赖

    1
    2
    3
    4
    5
    6
    <!-- Druid数据源依赖 -->
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.12</version>
    </dependency>
  • 创建Properties文件

    1
    2
    3
    4
    jdbc.driverClassName=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/test?userUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=Asia/Shanghai
    jdbc.username=root
    jdbc.password=p123456
  • 创建配置类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    package com.xiezhenyu.springbootjdbc.config;
    import com.alibaba.druid.pool.DruidDataSource;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    import javax.sql.DataSource;
    /**
    * 数据源jdbc的配置类
    */
    @Configuration
    @PropertySource("classpath:/jdbc.properties")//加载指定的properties配置文件
    public class JdbcConfiguration {
    @Value("${jdbc.driverClassName}")
    private String driverClassName;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;
    /**
    * 实例化Druid
    */
    @Bean
    public DataSource getDatasource(){
    DruidDataSource source = new DruidDataSource();
    source.setUsername(this.username);
    source.setPassword(this.password);
    source.setUrl(this.url);
    source.setDriverClassName(this.driverClassName);
    return source;
    }
    }
1.2.1.2、通过@ConfigurationProperties注解读取配置信息
  • 创建配置信息实体类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    /**
    * JDBC配置信息属性类
    */
    @ConfigurationProperties(prefix = "jdbc") //是SpringBoot的注解,不能读取其他的配置文件,只能读取SpringBoot的application配置文件
    public class JdbcProperties {
    private String driverClassName;
    private String url;
    private String username;
    private String password;
    public String getDriverClassName() {
    return driverClassName;
    }
    public void setDriverClassName(String driverClassName) {
    this.driverClassName = driverClassName;
    }
    public String getUrl() {
    return url;
    }
    public void setUrl(String url) {
    this.url = url;
    }
    public String getUsername() {
    return username;
    }
    public void setUsername(String username) {
    this.username = username;
    }
    public String getPassword() {
    return password;
    }
    public void setPassword(String password) {
    this.password = password;
    }
    }
  • 修改配置类

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    /**
    * 数据源jdbc的配置类
    */
    @Configuration
    @EnableConfigurationProperties(JdbcProperties.class)//指定加载哪个配置信息属性类
    public class JdbcConfiguration {
    @Autowired
    private JdbcProperties jdbcProperties;
    /**
    * 实例化Druid
    */
    @Bean
    public DataSource getDatasource(){
    DruidDataSource source = new DruidDataSource();
    source.setUsername(this.jdbcProperties.getUsername());
    source.setPassword(this.jdbcProperties.getPassword());
    source.setUrl(this.jdbcProperties.getUrl());
    source.setDriverClassName(this.jdbcProperties.getDriverClassName());
    return source;
    }
    }
1.2.1.3、@ConfigurationProperties注解的优雅使用方式

  在上面使用@ConfigurationProperties的时候,需要通过@ConfigurationProperties配置信息的实体类,进而在数据源配置类中通过注入的方式读取配置信息实体类,来获取信息。
  其实@ConfigurationProperties还可以在方法中使用当实例化Druid的时候可以直接在方法上添加@ConfigurationProperties注解,来获取配置信息。而这个注解就会自动把配置信息中的uername、password等数据自动调用DruidDataSource 的setUsername、setPassword等方法来设置信息。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* 数据源jdbc的配置类
*/
@Configuration
public class JdbcConfiguration {
/**
* 实例化Druid
*/
@Bean
@ConfigurationProperties(prefix = "jdbc")
public DataSource getDatasource(){
DruidDataSource source = new DruidDataSource();
return source;
}
}
1.2.2、通过Spring Boot配置文件配置数据源信息

  在Spring Boot1.x版本中的spring-boot-starter-jdbc启动器中默认使用的是org.apache.tomcat.jdbc.pool.DataSource作为数据源。
  在Spring Boot2.x版本中的spring-boot-starter-jdbc启动器默认使用的是com.zaxxer.hikariDataSource作为数据源。

1.2.2.1、使用Spring Boot默认的HikariDataSource数据源

  在application.properties中配置以下信息之后,在需要到数据源的时候直接注入即可。

1
2
3
4
spring.datasource.url=jdbc:mysql://localhost:3306/test?userUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=p123456

测试代码

1
2
3
4
5
6
7
8
9
@Controller
public class UsersController {
@Autowired
private DataSource dataSource;
@GetMapping("/showInfo")
public String showInfo(){
return "OK";
}
}
1.2.2.2、使用第三方的Druid数据源

  在application.properties配置文件中配置spring.datasource.type就可以更换数据源了。

1
2
3
4
5
spring.datasource.url=jdbc:mysql://localhost:3306/test?userUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=p123456
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

1.3、实现添加用户功能

1.3.1、创建POJO
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Users {
private Integer userid;
private String username;
private String usersex;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsersex() {
return usersex;
}
public void setUsersex(String usersex) {
this.usersex = usersex;
}
}
1.3.2、创建页面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
</head>
<body>
<from th:action="@{/user/addUser}" method="post">
<input type="text" name="username"/><br/>
<input type="text" name="usersex"/><br/>
<input type="submit" value="ok"/>
</from>
</body>
</html>
1.3.3、创建Controller
  • PageController

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    /**
    * 页面跳转Controller
    */
    @Controller
    public class PageController {
    //页面跳转方法
    @RequestMapping("/{page}")
    public String showPage(@PathVariable String page){
    return page;
    }
    }
  • UserController

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    @Controller
    @RequestMapping("/user")
    public class UsersController {
    @Autowired
    private UsersService usersService;
    @GetMapping("/showInfo")
    public String showInfo(){
    return "OK";
    }
    //添加用户
    @PostMapping("/addUser")
    public String addUser(Users users){
    try{
    this.usersService.addUser(users);
    }catch (Exception e){
    e.printStackTrace();
    return "error";
    }
    return "redirect:/ok";
    }
    }
1.3.4、创建Service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 用户管理业务层
*/
@Service
public class UserServiceImpl implements UsersService {
@Autowired
private UserDao userDao;

/**
* 添加用户
* @param users
*/
@Override
@Transactional
public void addUser(Users users) {
this.userDao.insertUsers(users);
}
}
1.3.5、创建Dao
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 用户管理持久层
*/
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;

/**
* 添加用户
* @param users
*/
@Override
public void insertUsers(Users users) {
String sql = "insert into user(username,usersex) values(?,?)";
this.jdbcTemplate.update(sql,users.getUsername(),users.getUsersex());
}
}
1.3.4、解决favicon.ico解析问题
1
<link rel="shortcut icon" href="../resource/favicon.ico" th:href="@{/static/favicon.ico}"/>

1.4、实现查询全部用户功能

1.4.1、修改Controller
1
2
3
4
5
6
7
8
9
10
11
12
13
//查询用户
@GetMapping("/showUser")
public String showUser(Model model){
List<Users> list = new ArrayList<>();
try{
list = this.usersService.showUsers();
}catch (Exception e){
e.printStackTrace();
return "error";
}
model.addAttribute("list",list);
return "showUser";
}
1.4.2、修改业务层
1
2
3
4
5
6
7
8
9
/**
* 查询用户
* @return
*/
@Override
@Transactional
public List<Users> showUsers(){
return this.userDao.showUsers();
}
1.4.3、修改持久层

使用RowMapper返回自定义对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
* 查询用户
* @return
*/
@Override
public List<Users> showUsers(){
String sql = "select * from user";
List<Users> users = this.jdbcTemplate.query(sql, new RowMapper<Users>() {
@Override
public Users mapRow(ResultSet resultSet, int i) throws SQLException {
Users user = new Users();
user.setUsername(resultSet.getString("username"));
user.setUsersex(resultSet.getString("usersex"));
user.setUserid(resultSet.getInt("userid"));
return user;
}
});
return users;
}
1.4.4、创建用户更新页面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
</head>
<body>
<table border="1" width="50%" align="center">
<tr>
<th>ID</th>
<th>用户名</th>
<th>性别</th>
<th>操作</th>
</tr>
<tr th:each="u : ${list}">
<td th:text="${u.userid}"></td>
<td th:text="${u.username}"></td>
<td th:text="${u.usersex}"></td>
<td>
<a th:href="@{/user/updateUser}">修改</a>
<a th:href="@{/user/deleteUser}">删除</a>
</td>
</tr>
</table>
</body>
</html>

1.5、实现用户更新功能

1.5.1、预更新查询
1.5.1.1、修改Controller
1
2
3
4
5
6
7
8
9
10
11
12
//预更新用户的查询
@GetMapping("/preUpdateUser")
public String preUpdateUser(Integer id,Model model){
try{
Users user = this.usersService.findUserById(id);
model.addAttribute("user",user);
}catch (Exception e){
e.printStackTrace();
return "error";
}
return "updateUser";
}
1.5.1.2、修改业务层
1
2
3
4
5
6
7
8
/**
* 用户预更新查询
*/
@Override
@Transactional
public Users findUserById(int id){
return this.userDao.selectUserById(id);
}
1.5.1.3、修改持久层
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 预更新用户查询
*/
public Users selectUserById(int id){
Users user = new Users();
String sql = "select * from user where userid = ?";
Object[] arr = new Object[]{id};
this.jdbcTemplate.query(sql, arr,new RowCallbackHandler() {
@Override
public void processRow(ResultSet resultSet) throws SQLException {
user.setUserid(resultSet.getInt("userid"));
user.setUsersex(resultSet.getString("usersex"));
user.setUsername(resultSet.getString("username"));
}
});
return user;
}
1.5.1.4、创建用户更新页面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Title</title>
</head>
<body>
<form th:action="@{/user/updateUser}" method="post">
<input type="hidden" name="userid" th:value="${user.userid}"/>
<input type="text" name="username" th:value="${user.username}"/><br/>
<input type="text" name="usersex" th:value="${user.usersex}"/><br/>
<input type="submit" value="修改"/>
</form>
</body>
</html>
1.5.2、更新用户
1.5.2.1、修改Controller
1
2
3
4
5
6
7
8
9
10
11
//更新用户
@PostMapping("/updateUser")
public String updateUser(Users user){
try{
this.usersService.modifyUser(user);
}catch (Exception e){
e.printStackTrace();
return "error";
}
return "ok";
}
1.5.2.2、修改业务层
1
2
3
4
5
6
7
8
9
/**
* 用户更新
* @param user
*/
@Override
@Transactional
public void modifyUser(Users user){
this.userDao.updateUser(user);
}
1.5.2.3、修改持久层
1
2
3
4
5
6
7
/**
* 更新用户
*/
public void updateUser(Users user){
String sql = "update user set username = ?,usersex = ? where userid = ?";
jdbcTemplate.update(sql,user.getUsername(),user.getUsersex(),user.getUserid());
}
1.5.3、删除用户
1.5.3.1、修改Controller
1
2
3
4
5
6
7
8
9
10
11
//删除用户
@GetMapping("/deleteUser")
public String deleteUser(Integer id){
try{
this.usersService.dropUser(id);
}catch (Exception e){
e.printStackTrace();
return "error";
}
return "redirect:/ok";
}
1.5.3.2、修改业务层
1
2
3
4
5
6
7
/**
* 删除用户
*/
@Override
public void dropUser(Integer id){
this.userDao.deleteUser(id);
}
1.5.3.3、修改持久层
1
2
3
4
5
6
7
/**
* 删除用户
*/
public void deleteUser(Integer id){
String sql = "delete from user where userid = ?";
jdbcTemplate.update(sql,id);
}